package com.yifeng.repo.base.encryption.handler;

import com.google.common.base.Strings;
import com.yifeng.repo.base.encryption.DataGuarder;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by daibing on 2023/9/18.
 */
public class EncryptTypeHandler extends BaseTypeHandler {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, DataGuarder.encrypt((String) parameter));
    }

    @Override
    public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String columnValue = rs.getString(columnName);
        return Strings.isNullOrEmpty(columnValue) ? null : DataGuarder.decrypt(columnValue);
    }

    @Override
    public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String columnValue = rs.getString(columnIndex);
        return Strings.isNullOrEmpty(columnValue) ? null : DataGuarder.decrypt(columnValue);
    }

    @Override
    public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String columnValue = cs.getString(columnIndex);
        return Strings.isNullOrEmpty(columnValue) ? null : DataGuarder.decrypt(columnValue);
    }
}
